import http from '@/utils/http'
import router from '@/router'
let token=localStorage.getItem("Authorization")
let UserInfo=JSON.parse(localStorage.getItem("UserInfo"))
let permissions=JSON.parse(localStorage.getItem("permissions"))
export default{
    namespaced:true,
    state(){
        return {
            Authorization:token,
            UserInfo:UserInfo,
            permissions:permissions
        }
    },
    getters:{
        islogin(state){
            return !!state.Authorization;
        }
    },
    mutations:{
        login(state,payload){//登录 把token和用户信息存储起来
            state.Authorization=payload.Authorization;
            state.UserInfo=payload;
            localStorage.setItem("Authorization",payload.Authorization)
            localStorage.setItem("UserInfo",JSON.stringify(payload));
        },
        logOut(state){
            state.Authorization=null;
            state.UserInfo=null;
            state.permissions=null;
            localStorage.clear();
            router.push("/login");
        },
        setPermissions(state,payload){
            state.permissions=payload;
            localStorage.setItem("permissions",JSON.stringify(payload));
        }   
    },
    actions:{
        async asyncLogin(context,payload){
            let re=await http.get("/user/login",{params:payload});
            // console.log("re===>",re);
            if(re&&re.Authorization){
                context.commit("login",re);
                ElMessage({
                    type:"success",
                    message:"登录成功"
                });
                router.push("/manage");
            }else{
                ElMessage({
                    type:"error",
                    message:"账号密码错误登录失败!"
                })
            }
        },
        async getPermission({commit,state,rootState},payload){//this.$store
            // context.commit();
            if (!state.UserInfo) return;
            let permissions=await http.get("/admin/role",{params:{userid:state.UserInfo._id}});
            console.log("permissions===>",permissions);
            commit("setPermissions",permissions);
        }
    },
    modules:{}
}